package com.global.college.ui.activity;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.global.college.CollegeApplication;
import com.global.college.R;
import com.global.college.base.BaseActivity;
import com.global.college.base.PayResult;
import com.global.college.utils.ToastUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;

import java.util.Map;

import pay.AuthResult;

/**
 * 支付
 */
public class PayActivity extends BaseActivity {

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    private IWXAPI mWxapi;
    private Handler mHandler = new Handler() {
        @SuppressLint("HandlerLeak")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultMemo = payResult.getMemo();// 同步返回需要验证的信息
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    if (TextUtils.equals(resultStatus, "9000")) {// 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastUtils.showToastShort("支付成功!");
                    } else if ((TextUtils.equals(resultStatus, "8000"))) {
                        ToastUtils.showToastShort("支付结果未知!");
                        //finish();
                    } else if ((TextUtils.equals(resultStatus, "4000"))) {
                        ToastUtils.showToastShort("订单支付失败!");
                        //finish();
                    } else if ((TextUtils.equals(resultStatus, "5000"))) {
                        ToastUtils.showToastShort("重复请求!");
                        //finish();
                    } else if ((TextUtils.equals(resultStatus, "6001"))) {
                        ToastUtils.showToastShort("支付已取消!");
                        //finish();
                    } else if ((TextUtils.equals(resultStatus, "6002"))) {
                        ToastUtils.showToastShort("网络异常!");
                        //finish();
                    } else {
                        ToastUtils.showToastShort("未知错误!");
                        //finish();
                    }
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        ToastUtils.showToastShort("授权成功!");
                    } else {
                        // 其他状态值则为授权失败
                        ToastUtils.showToastShort("授权失败"+authResult);
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };
    @Override
    public int getContentViewId() {
        return R.layout.activity_pay;
    }

    @Override
    public void onCreateNew(Bundle savedInstanceState) {

    }

    @Override
    public void getInitData() {
        AliPay();
        WxPay();
    }

    private void WxPay() {
            //appId
            String appid = "payBean.getData().getAppid()";
            //随机字符串
            String noncestr = "payBean.getData().getNoncestr()";
            //扩展字段
            String packageX = "payBean.getData().getPackageX()";
            //微信返回的支付交易会话ID
            String partnerid = "payBean.getData().getPartnerid()";
            String prepayid = "payBean.getData().getPrepayid()";
            //时间戳
            String timestamp = "payBean.getData().getTimestamp()" + "";
            //签名
            String sign = "payBean.getData().getSign()";

            //微信参数
            final PayReq req = new PayReq();
            req.appId = appid;
            req.nonceStr = noncestr;
            req.packageValue = packageX;
            req.partnerId = partnerid;
            req.prepayId = prepayid;
            req.timeStamp = timestamp;
            req.sign = sign;
            mWxapi = CollegeApplication.getInstance().getmWxApi();
            mWxapi.registerApp(appid);
            //在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            mWxapi.sendReq(req);
    }

    private void AliPay() {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);
                Map<String, String> result = alipay.payV2("model.getD().getSign()", true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
}